package com.tjbank.cssys.framework.base.util;

import com.tjbank.cssys.framework.base.exception.ServiceException;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;



/**
 * 获取Spring上下文对象
 * 
 * Package : com.tansun.magicube.framework.base.util
 * 
 * @author -- lijiangtao 2020年4月7日 下午5:14:29
 *
 */
@Component
public class ApplicationContextHelper implements ApplicationContextAware {

    // 上下文对象实例
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextHelper.applicationContext = applicationContext;
    }

    /**
     * 获取applicationContext
     * 
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 通过name获取 Bean.
     * 
     * @param name
     * @return
     */
    public static Object getBean(String name) {
        ApplicationContextHelper.applicationContext.getBean(name);
        return getApplicationContext().getBean(name);
    }

    /**
     * 通过class获取Bean.
     * 
     * @param <T>
     * @param targetClz
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(Class<T> targetClz) {
        T beanInstance = null;
        // 优先按type查
        try {
            beanInstance = (T) applicationContext.getBean(targetClz);
        } catch (Exception e) {
        }
        // 按name查
        if (beanInstance == null) {
            String simpleName = targetClz.getSimpleName();
            // 首字母小写
            simpleName = Character.toLowerCase(simpleName.charAt(0)) + simpleName.substring(1);
            beanInstance = (T) applicationContext.getBean(simpleName);
        }
        if (beanInstance == null) {
            new ServiceException("Component " + targetClz + " can not be found in Spring Container");
        }
        return beanInstance;
    }

    /**
     * 通过name,以及Clazz返回指定的Bean
     *
     * @param name
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }

}